package pl.edu.agh.neuraleconomy.dataimporter.xls;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

public class HistoryDataDownloader {
	private Logger logger = Logger.getLogger(getClass());
	
	private static final String URL_FORMAT = "http://www.gpw.pl/notowania_archiwalne?type=10&date=%s&fetch.x=20&fetch.y=17";
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	public InputStream getHistoryByDate(Date date) {
		logger.info("Pobieram dane historyczne dla " + dateFormat.format(date));
		
		BufferedInputStream bis = null;
		try {
			URL urlPath = new URL(String.format(URL_FORMAT, dateFormat.format(date)));
			URLConnection conn = urlPath.openConnection();	
			bis = new BufferedInputStream(conn.getInputStream());
			return bis;
		} catch (Exception e) {
			logger.error("Nie udalo sie pobrac danych historycznych z " + dateFormat.format(date), e);
			IOUtils.closeQuietly(bis);
			return null;
		}
	}	
}
